'use strict';
let fs = require('fs');
let path = require('path');
module.exports = {
    createPromiseCallback,
    timeInterval,
    parsePromiseCallback,
    getBackName,
    noop: () => {
    }
};

/**
 * 返回一个异常优先的回调函数
 * @return {*}
 */
function createPromiseCallback() {
    let cb;
    let promise = new Promise(function(resolve, reject) {
        cb = function(err, data) {
            if (err) return reject(err);
            return resolve(data);
        };
    });
    cb.promise = promise;
    return cb;
}

/**
 * 转换某个函数为promise对象
 * @param fn
 * @param context 当前函数的上下文对象
 * @return {*}
 */
function parsePromiseCallback(fn, context) {
    let cb;
    let promise = new Promise(function(resolve, reject) {
        cb = function(...args) {
            context = context || this;
            fn.call(context, ...args, function(err, ...args) {
                if (err) return reject(err);
                args = args.length ? args.length === 1 ? args[0] : args : undefined;
                return resolve(args);
            });
            return promise;
        };
    });
    cb.promise = promise;
    return cb;
}

let humanize = require('ms');

/**
 * 获取每次调用之间的时间间隔,间隔对象挂在process上
 * @param cb
 * @return {*}
 */
function timeInterval(cb) {
    if (!process.customTimeInterval) {
        process.customTimeInterval = {
            diff: 0,
            prev: 0,
            curr: 0,
            start: +new Date(),
        };
    }
    let current = process.customTimeInterval;

    let curr = +new Date();
    let ms = curr - (current.curr || curr);
    current.diff = ms;
    current.prev = current.curr || curr;
    current.curr = curr;
    if (cb) {
        return cb(humanize(ms), current, humanize);
    }
    return humanize(ms);
}

/**
 * 获取备份文件名，备份扩展名为自增数字 file.js,file.js.1,file.js.2
 * @param filename
 * @param cb,不提供返回promise
 */
function getBackName(filename, cb) {
    cb = cb || createPromiseCallback();
    fs.access(filename, function(err) {
        if (err) {
            if (err.errno === -2) {
                cb(null, filename);
            } else {
                cb(err);
            }
        } else {
            let extname = path.extname(filename);
            let newext = '';
            if (extname && Number(extname.substr(1))) {
                newext = '.' + (extname.substr(1) * 1 + 1).toString();
            } else {
                newext = extname + '.1';
            }
            getBackName(filename.replace(extname, newext), cb);
        }
    });
    return cb.promise;
}
